import 'dart:convert';

import 'package:elephant_fish/TRTCChatSalonDemo/model/TRTCChatSalon.dart';
import 'package:elephant_fish/TRTCChatSalonDemo/model/TRTCChatSalonDef.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/model/voice_room_entity.dart';
import 'package:elephant_fish/page/login_page.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class VoiceList extends StatefulWidget {
  final VoiceRoomEntity voiceRoomEntity;
  const VoiceList({Key key, this.voiceRoomEntity}) : super(key: key);

  @override
  _VoiceListState createState() => _VoiceListState();
}

class _VoiceListState extends State<VoiceList> {

  ScrollController _scrollController = ScrollController();
  TRTCChatSalon trtcVoiceRoom;
  List<Widget> list = List();
  UserInfoEntity userInfoEntity;
  bool isEnter = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getInitData();
    getUserList();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Container(
        child: Stack(
          children: [
            Padding(padding: EdgeInsets.only(left: 10,top: 22.5,right: 10),
              child: Card(
                margin: EdgeInsets.only(left: 10,right: 10),
                color: Color(0x5059527a),
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(5),
                    child:
                    Stack(
                      children: [
                        Padding(padding: EdgeInsets.only(left: 77.5,top: 14),
                          child: Text(widget.voiceRoomEntity.title ,style: TextStyle(fontSize: 13,color: Color(0xfff3f3f3)),),
                        ),
                        SizedBox(width: size.width,
                          height: 100,
                          child:   ListView.builder(
                              scrollDirection: Axis.horizontal,
                              itemCount: list.length,
                              controller: _scrollController,
                              shrinkWrap: true,
                              physics: NeverScrollableScrollPhysics(),
                              itemBuilder:(context,index){
                                return list[index];
                              }
                          ),
                        ),

                        // Row(
                        //   children: [
                        //     Padding(padding: EdgeInsets.only(left:17.5,top: 54.5,bottom: 13.5 ),
                        //       child: Image.asset('assets/images/empty.png',width: 32,),
                        //     ),
                        //     Padding(padding: EdgeInsets.only(left:6.5,top: 54.5,bottom: 13.5 ),
                        //       child: Image.asset('assets/images/empty.png',width: 32,),
                        //     ),
                        //     Padding(padding: EdgeInsets.only(left:6.5,top: 54.5,bottom: 13.5 ),
                        //       child: Image.asset('assets/images/empty.png',width: 32,),
                        //     ),
                        //     Padding(padding: EdgeInsets.only(left:6.5,top: 54.5,bottom: 13.5 ),
                        //       child: Image.asset('assets/images/empty.png',width: 32,),
                        //     ),
                        //     Padding(padding: EdgeInsets.only(left:6.5,top: 54.5,bottom: 13.5 ),
                        //       child: Image.asset('assets/images/empty.png',width: 32,),
                        //     ),
                        Align(
                          alignment: Alignment.topRight,
                          child:  Padding(padding: EdgeInsets.only(right:10,top: 47.5,bottom: 12.5),
                            child: InkWell(
                              onTap: (){
                                if(isEnter){
                                  RoomInfo roomInfo = RoomInfo(roomId: widget.voiceRoomEntity.roomId,
                                      roomName: widget.voiceRoomEntity.title,
                                      coverUrl: widget.voiceRoomEntity.owner.avatar,
                                      memberCount: widget.voiceRoomEntity.person,
                                      ownerId: widget.voiceRoomEntity.owner.userId,
                                      ownerName: widget.voiceRoomEntity.owner.nickname
                                  );
                                  goRoomInfoPage(roomInfo);
                                }else{
                                  TxUtils.showToast('您的等级或权限不足，无法进入', context);
                                }

                              },
                              child: Image.asset('assets/images/enter_room.png',width: 82,
                              ),
                            ),
                          ),
                        ),

                        // ],
                        // )

                      ],
                    )
                ),
              ),
            ),
            Padding(padding: EdgeInsets.only(top: 15,left: 33.0),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: Image.network('http://119.28.131.94:82' + widget.voiceRoomEntity.owner.avatar,width: 53,height: 53,fit: BoxFit.cover,),
                )
            ),
          ],
        )
    ) ;
  }

  Future<void> getUserList() async {
    for(int i = 0; i < widget.voiceRoomEntity.users.length;i++){
      list.add(Padding(padding: EdgeInsets.only(left:6.5,top: 54.5,bottom: 13.5 ),
        child: Image.network('http://119.28.131.94:82' + widget.voiceRoomEntity.users[i].avatar,width: 32,),
      ));
    }
    if(widget.voiceRoomEntity.users.length < 5){
      for(int i = widget.voiceRoomEntity.users.length; i < 5; i++ ){
        list.add(Padding(padding: EdgeInsets.only(left:17.5,top: 54.5,bottom: 13.5 ),
          child: Image.asset('assets/images/empty.png',width: 32,),
        ));
      }
    }
    trtcVoiceRoom = await TRTCChatSalon.sharedInstance();
  }



  createVoiceRoom(int roomId) async {
      await TxUtils.setStorageByKey("loginUserName", widget.voiceRoomEntity.owner.nickname);
      String ownerId = await TxUtils.getLoginUserId();
      Navigator.popAndPushNamed(
        context,
        "/chatSalon/roomAnchor",
        arguments: {
          "coverUrl":  widget.voiceRoomEntity.owner.avatar,
          "roomName":  widget.voiceRoomEntity.owner.nickname,
          "roomId": widget.voiceRoomEntity.roomId,
          "ownerId": widget.voiceRoomEntity.owner.userId,
          'isNeedCreateRoom': true,
        },
      );
  }

  goRoomInfoPage(RoomInfo roomInfo) async {
    String loginUserId = await TxUtils.getLoginUserId();
    if (roomInfo.ownerId.toString() == loginUserId) {
      await trtcVoiceRoom.setSelfProfile(
        roomInfo.ownerName,
        'http://119.28.131.94:82' + roomInfo.coverUrl,
      );
      await TxUtils.setStorageByKey("loginUserName",roomInfo.ownerName);
      String ownerId = await TxUtils.getLoginUserId();
      Navigator.popAndPushNamed(
        context,
        "/chatSalon/roomAnchor",
        arguments: {
          "coverUrl": 'http://119.28.131.94:82' + roomInfo.coverUrl,
          "roomName":  roomInfo.ownerName,
          "roomId": roomInfo.roomId,
          "ownerId": roomInfo.ownerId,
          'isNeedCreateRoom': true,
        },
      );
      // Navigator.pushReplacementNamed(
      //   context,
      //   "/chatSalon/roomAudience",
      //   arguments: {
      //     'roomId': roomInfo.roomId,
      //     "ownerId": roomInfo.ownerId,
      //     "roomName": roomInfo.roomName,
      //     'isNeedCreateRoom': false,
      //   },
      // );
      return;
    }
    Navigator.pushReplacementNamed(
      context,
      "/chatSalon/roomAudience",
      arguments: {
        "ownerId": roomInfo.ownerId,
        "roomName": roomInfo.roomName,
        'roomId': roomInfo.roomId,
        'isNeedCreateRoom': false,
      },
    );
  }

  Future<void> getInitData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserInfoRequest();
    request.add('type', 2).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
    setState(() {
      userInfoEntity = UserInfoEntity.fromJson(
          new Map<String, dynamic>.from(result['data']));
      if(widget.voiceRoomEntity.joinLevel > userInfoEntity.level){
        isEnter = false;
      }
    });
  }

}
